#include "MyMsgOut.h"

#include <cstdlib>
#include <cstdio>
#include <enet/enet.h>
#include <iostream>

const unsigned int kInitialDataSize = 16;
const unsigned int kSizeDataMultiplier = 2;

MyMsgOut::MyMsgOut():
    mDataSize(kInitialDataSize),mPos(0)
{
    mData = (char*) malloc(kInitialDataSize);
}

MyMsgOut::~MyMsgOut()
{
    free(mData);
}

char *MyMsgOut::GetData() const
{
    return mData;
}

unsigned int MyMsgOut::GetLength() const
{
    return mPos;
}

void MyMsgOut::Expand(unsigned int bytesToAdd)
{
    unsigned int bytes = mPos+bytesToAdd;
    if (bytes > mDataSize)
    {
        do
        {
            mDataSize *= kSizeDataMultiplier;
        }
        while (bytes > mDataSize);
        mData = (char*) realloc(mData, mDataSize);
    }
}

void MyMsgOut::WriteId(const int &id)
{
    Write2Bytes(id);
}

void MyMsgOut::WriteString(const std::string &str)
{
    int length = str.length();
    Write2Bytes(length);
    Expand(length);
    memcpy(mData + mPos, str.c_str(), length);
    mPos += length;
}

void MyMsgOut::Write2Bytes(const int &val)
{
    Expand(2);
    uint16_t t = ENET_HOST_TO_NET_16(val);
    memcpy(mData + mPos, &t, 2);
    mPos += 2;
}
